package com.gooluke.mds.service.impl;

import com.gooluke.mds.common.annotation.MapperMultiDataSource;
import com.gooluke.mds.common.annotation.MultiDataSource;
import com.gooluke.mds.common.constants.DataSourceName;
import com.gooluke.mds.dao.UserInfoDao;
import com.gooluke.mds.dao.UserInfoDao2;
import com.gooluke.mds.domain.entity.TUserInfo;
import com.gooluke.mds.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author gooluke
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private UserInfoDao2 userInfoDao2;

    /**
     * 在这里没有设置数据源，dao层设置了数据源，可以自动切换
     */
    @Override
    public List<TUserInfo> selectList() {
        List<TUserInfo> tUserInfos = userInfoDao.selectUserList(new TUserInfo());
        tUserInfos.forEach(System.out::println);
        List<TUserInfo> tUserInfos2 = userInfoDao2.selectUserList(new TUserInfo());
        tUserInfos2.forEach(System.out::println);
        tUserInfos.addAll(tUserInfos2);
        return tUserInfos;
    }

    @Override
    @MultiDataSource(names = {DataSourceName.SHANGHAI_01, DataSourceName.SHANGHAI_02})
    public int insertUser(TUserInfo userInfo) {
        String randomString = RandomStringUtils.random(10, "0123456789");
        TUserInfo user = buildUser(randomString);
        int i = userInfoDao.insertUser(user);
        Random random = new Random();
        int a = random.nextInt(3) + 1;
        System.out.println("a = " + a);
        if (a % 3  == 0) {
            throw new RuntimeException("系统异常");
        }
        return i;
    }

    @Override
    @MapperMultiDataSource(names = {DataSourceName.SHANGHAI_01, DataSourceName.SHANGHAI_02})
    public int insertUser2(TUserInfo userInfo) {
        log.info("开始执行方法insertUser2");
        String randomString = RandomStringUtils.random(10, "0123456789");
        TUserInfo user = buildUser(randomString);
        int result1 = userInfoDao.insertUser(user);
        TUserInfo user2 = buildUser(randomString + "_2");
        int result2 = userInfoDao.insertUser(user2);
        Random random = new Random();
        int a = random.nextInt(3) + 1;
        System.out.println("a = " + a);
        if (a % 3  == 0) {
            throw new RuntimeException("系统异常");
        }
        log.info("执行方法insertUser2结束");
        return 1;
    }

    private TUserInfo buildUser(String random) {
        TUserInfo user = new TUserInfo();
        user.setUserName("user_name_" + random);
        user.setUserId("userid_" + random);
        user.setPassword(random);
        user.setAddress("address_" + random);
        user.setNickName("nick_name_" + random);
        user.setPhone(random);
        return user;
    }

}
